package org.csu.mypetstore.web.servlet;

import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AddItemToCartServlet", value = "/AddItemToCartServlet")
public class AddItemToCartServlet extends HttpServlet {
    //1.处理完请求跳转的画面
    private static final String VIEW_CART="/WEB-INF/jsp/cart/Cart.jsp";
    //2.定义处理该请求所需要的数据
    private String workingItemId;
    private Cart cart;
    //3.是否需要调用业务逻辑层

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        workingItemId=request.getParameter("workingItemId");
        HttpSession session=request.getSession();
        cart = (Cart)session.getAttribute("cart");

        if(cart==null){
            cart=new Cart();
        }
        if(cart.containsItemId(workingItemId)) {
            cart.incrementQuantityByItemId(workingItemId);
        }else{
            CatalogService catalogService = new CatalogService();//新建报错了加了一个CatalogService
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item,isInStock);
        }
        session.setAttribute("cart",cart);
        request.getRequestDispatcher(VIEW_CART).forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
